var PRO = PRO || {};
PRO.fullcalendar = (function () {
	var callbacks = $.Callbacks();
	//初始化日程
	function _initSchedule(url, fnClick){
		$("#calendar").fullCalendar({
			events: url,
			eventClick: function (obj) {
				fnClick && fnClick(obj);
			}
		});
		_bgToday(); //周视图和日视图中高亮显示今天
		/**下拉筛选**/
		$('.nore-filter-select').hover(function(){
			$('.nore-filter-panel').show();
		},function(){
			$('.nore-filter-panel').hide();
		});
		$('body').on('click','.nore-filter-item',function(){
			$('.nore-filter-txt').text($(this).find('span').text());
			$('.nore-filter-panel').hide();
		});
	}
	//新建日程
	function _newSchedule() {
		$(document).on("click", "#btn_new_schedule,#a_new_schedule", function () {
			var $this = $(this);
			callbacks.add($.removeLoading);
			callbacks.add(PRO.customerUnit.createCalendar);
			callbacks.add(saveNewScheduleV2);
			var obj = {
				'selector':$(this),
				'btnShow':'true',
				'hbgc':'#f5f5f5',
				'hr':50,
				'title':'新建日程'
			};
			PRO.formDialog.openDialog(ctx+'/sys/schedule/schedule/dialog/new',651,callbacks,obj);
		}).on("change", "#slt_schedule_type", function () {
		}).on("change", "#slt_repeat", function () {
			//选择重复select事件
			$("#sp_unit").text( $(this).find("option:selected").attr("data-text") + $(this).find("option:selected").data("remark"));
		}).on("click", "#isFinishedYes", function () {
			//选择日程重复截止日期
			if ($(this).is(':checked')) {
				$("#txt_repeat_end").show();
			} else {
				$("#txt_repeat_end").hide();
				$("#txt_repeat_end").val("");
			}	
		}).on("click", "#isFinishedNo", function () {
			//选择日程重复截止日期
			if ($(this).is(':checked')) {
				// $("#txt_repeat_end").prop("disabled", true);
				$("#txt_repeat_end").hide();
				$("#txt_repeat_end").val("");
			}
		}).on("click", "#isFinishedYes", function () {
			//选择日程重复截止日期
			if ($(this).is(':checked')) {
				// $("#txt_repeat_end").prop("disabled", true);
				$("#txt_repeat_end").show();
			}
		}).on('click', 'a.rightCommonSchedule', function() {
			var id=$(this).attr("data-id");
			var start=$(this).attr("data-starttime");
			var end=$(this).attr("data-endtime");
			var type=$(this).attr("data-type");
			if(type=="0"){
				type="其他";
			}else{
				type="事项";
			}
			var $this = this;
			url=ctx+"/sys/schedule/schedule/detail"+"?id="+id+"&start="+start+"&end="+end;
			$.ajax({
				url:ctx+ '/sys/schedule/schedule/isCreateUser',
				type: 'POST',
				dataType: 'json',
				async : false,
				data:{id:id}
			})
			.done(function(data) {
				if(data){
					openEditDialog(url, true);
				}else{
					openEditDialog(url, false);
				}
			}).fail(function(e) {
				parent.layer.alert("获取日程详情,请刷新页面后重试!", 0);
			});
		});
		$("body").on('click', '#cbx_repeat', function(event) {
			var container = $(this).closest('.dialog-checkbox-row').find('.dialog-row-hiddenContent');
			if ($(this).is(":checked")) {
				container.find('.chosen-container').css('width', 'auto');
				container.show();
			}else{
				container.hide();
			}
		});
		$("body").on('click', '#cbx_allday', function(event) {
			var val = $("#slt_schedule_type").val();
			if (val == "meeting"){
				var container = $(this).closest('.dialog-layer');
				if ($(this).is(":checked")) {
					container.find('.timeRow .dialog-select').prop('disabled',true).trigger("chosen:updated");
				}else{
					container.find('.timeRow .dialog-select').prop('disabled',false).trigger("chosen:updated");
				}
				$("div[_tag='matter'] select").prop("disabled",true)
			}else{
				var container = $(this).closest('.dialog-layer');
				if ($(this).is(":checked")) {
					container.find('.timeRow .dialog-select').prop('disabled',true).trigger("chosen:updated");
				}else{
					container.find('.timeRow .dialog-select').prop('disabled',false).trigger("chosen:updated");
				}
				$("div[_tag='meeting'] select").prop("disabled",true)
			}
		});
	}
	//编辑日程
	function _editSchedule(url, id, type, index) {
		var $this = $(this);
		callbacks.add(PRO.customerUnit.createCalendar);
		callbacks.add(editScheduleV2);
		var obj = {
				'selector':$(this),
				'btnShow':'true',
				'hbgc':'#f5f5f5',
				'hr':50
			};
		PRO.formDialog.openDialog(url+"?id="+id, 651, callbacks, obj);
	}
	//查看详情
	function _showSchedule(url, id, type,start,end,allDay) {
		if(allDay){
			if(start){
				start=start.format("yyyy-MM-dd");
			}
			if(!end){
				end=start;
			}else{
				end=end.format("yyyy-MM-dd");
			}
		}else{
			if(start){
				start=start.format("yyyy-MM-dd hh:mm");
			}
			if(!end){
				end=start;
			}else{
				end=end.format("yyyy-MM-dd hh:mm");
			}
		}
		url=url+"?id="+id+"&start="+start+"&end="+end;
		$this = $(this);

        $.ajax({
            url:ctx+ '/sys/schedule/schedule/isCreateUser',
            type: 'POST',
            dataType: 'json',
            async : false,
            data:{id:id}
        })
		.done(function(data) {
			if(data.data){
				openEditDialog(url, true);
			}else{
				openEditDialog(url, false);
			}
		})
		.fail(function(e) {
			parent.layer.alert("获取日程详情,请刷新页面后重试!", 0);
		});
	}
	
	function openEditDialog(url, isCreateUser){
		if(isCreateUser){
			var obj = {
					'selector':$(this),
					'bgc':'#eef0f3',
					'btnShow':'true',
					'btnArr':[{'txt':'编辑','classClick':'dg-btn-edit','btnColor':'dg-btn-blue'},{'txt':'删除','classClick':'dg-btn-del','btnColor':'dg-btn-white'}],
					'hr':30
				};
            obj.title="事项详情";
			PRO.formDialog.openDialog(url, 400, callbacks, obj);
		}else{
			var obj = {
					'selector':$(this),
					'bgc':'#eef0f3',
					'btnShow':'false',
					'hr':30
				};
			PRO.formDialog.openDialog(url, 400, callbacks, obj);
		}
	}
	


	//表单基础验证
	function _validate() {
		var sDate = $("#txt_start_date").val(), eDate = $("#txt_end_date").val(),
			 sTime = $("#slt_start_time").val(), eTime= $("#slt_end_time").val(),
			chkAllDay = $("#cbx_allday").prop("checked"), chkRepeat = $("#cbx_repeat").prop("checked"), chkRepeatEnd = $("#isFinishedYes").prop("checked"),
			sltRepeat = $("#slt_repeat").val(), sltType = $("#slt_schedule_type").val(), txtCount = $("#intervalNum").val(), txtRepeatEnd = $("#txt_repeat_end").val();
		var meeting_name=$("#meeting_name").val();
		var matter_name=$("#matter_name").val();
		var sDateTmp;
			if(!matter_name){
				parent.layer.alert("请输入事项名称！", 0);
				return false;
			}
			if (!sDate) {
				parent.layer.alert("请输入事项开始日期！", 0);
				return false;
			} if (!eDate) {
			parent.layer.alert("请输入事项结束日期！", 0);
				return false;
			} 
			if (_diffDays(sDate, eDate) < 0) {
				parent.layer.alert("事项结束日期不能小于开始日期!", 0);
				return false;
			} if (_diffDays(sDate, eDate) > 366) {
			parent.layer.alert("事项开始和结束日期之间不能超过一年！", 0);
				return false;
			} if (!chkAllDay && _diffDays(sDate, eDate)==0 &&_diffTimes(sTime, eTime) <= 0) {
			parent.layer.alert("结束时间必须大于开始时间！", 0);
				return false;
			} 
			sDateTmp=sDate;
		if (chkRepeat && !txtCount) {
			parent.layer.alert("请填写重复频率！", 0);
			return false;
		} if (chkRepeat && parseInt(txtCount) == 0) {
			parent.layer.alert("重复频率不能为0！", 0);
			return false;
		} if (chkRepeat && chkRepeatEnd && !txtRepeatEnd) {
			parent.layer.alert("请选择重复截止日期！", 0);
			return false;
		}if (chkRepeat && chkRepeatEnd && txtRepeatEnd && _diffDays(sDateTmp, txtRepeatEnd)<0) {
			parent.layer.alert("重复截止日期不能小于开始时间！", 0);
			return false;
		} if (chkRepeat && sltRepeat == "01" && parseInt(txtCount) > 30) {
			parent.layer.alert("每日重复不能超过30天！", 0);
			return false;
		} if (chkRepeat && sltRepeat == "02" && parseInt(txtCount) > 12) {
			parent.layer.alert("每周重复不能超过12周!", 0);
			return false;
		} if (chkRepeat && sltRepeat == "03" && parseInt(txtCount) > 24) {
			parent.layer.alert("每月重复不能超过24个月!", 0);
			return false;
		} if (chkRepeat && sltRepeat == "04" && parseInt(txtCount) > 30) {
			parent.layer.alert("每年重复不能超过30年!", 0);
			return false;
		}if(!$("#managerId").val()){
			parent.layer.alert("请选择事项参与人", 0);
            return false;
        }

		return true;
	}
	//保存新建日程
	function saveNewSchedule(index, bRight){
		var createData=$("#save_form").form2Json();
		if(createData.isAllDay&&createData.isAllDay=="on"){
			createData.isAllDay=true;
		}else{
			createData.isAllDay=false;
		}
		if(createData.isRepeat&&createData.isRepeat=="on"){
			createData.isRepeat=true;
		}else{
			createData.isRepeat=false;
		}
		//重复截止该参数做相反的处理
		if(createData.isRepeatForever&&createData.isRepeatForever=="0"){
			createData.isRepeatForever=false;
		}else{
			createData.isRepeatForever=true;
		}
		//获取参与人
		createData["scheduleUsersStr"]=$("#managerId").val();
		$.ajax({
			url: ctx+'/sys/schedule/schedule/saveNew',
			type: 'POST',
			dataType: 'json',
			data:createData
		})
		.done(function(data) {
			if(data&&data.isSuccess){
				layer.alert(data.msg, {"offset":["40%","25%"]},function(){
                        window.location.reload();
				});
			}else{
				parent.layer.alert("保存失败")
			}
		}).fail(function(e) {
			parent.layer.alert("保存失败")
		});
	}
	//改变编辑窗的显示效果
	function changeEditDialogState(){
		var createData=$("#save_form").form2Json();
		if(createData.isAllDay&&createData.isAllDay=="on"){
			createData.isAllDay=true;
		}else{
			createData.isAllDay=false;
		}
		if(createData.isRepeat&&createData.isRepeat=="on"){
			createData.isRepeat=true;
		}else{
			createData.isRepeat=false;
		}
		//重复截止该参数做相反的处理
		if(createData.isRepeatForever&&createData.isRepeatForever=="0"){
			createData.isRepeatForever=false;
		}else{
			createData.isRepeatForever=true;
		}
		//获取参与人
		createData["scheduleUsersStr"]=$("#managerId").val();
		$.ajax({
			url: ctx+'/sys/schedule/schedule/saveNew',
			type: 'POST',
			dataType: 'json',
			data:createData
		})
			.done(function(data) {
				if(data&&data.isSuccess){
					layer.alert(data.msg, function(){
							window.location.reload();
					});
				}else{
					parent.layer.alert("保存失败")
				}
			}).fail(function(e) {
			parent.layer.alert("保存失败")
		});
	}
	

	
	function saveModifySchedule(){
		var createData=$("#save_form").form2Json();
		if(createData.isAllDay&&createData.isAllDay=="on"){
			createData.isAllDay=true;
		}else{
			createData.isAllDay=false;
		}
		if(createData.isRepeat&&createData.isRepeat=="on"){
			createData.isRepeat=true;
		}else{
			createData.isRepeat=false;
		}
		//获取参与人
		createData["scheduleUsersStr"]=$("#managerId").val();
		$.ajax({
			url: ctx+'/sys/schedule/schedule/saveEdit',
			type: 'POST',
			dataType: 'json',
			data:createData
		}).done(function(data) {
				if(data&&data.isSuccess){
					layer.alert(data.msg, {"offset":["40%","25%"]},function(){
						//如果通过首页右侧删除，则整页刷新
							window.location.reload();
					});
				}else{
					parent.layer.alert("保存失败")
				}
			}).fail(function(e) {
			parent.layer.alert("保存失败")
		});
	}
	//删除
	function delSchedule(bRight){
		var scheduleId =$("#scheduleId").val();
		$.ajax({
			url: ctx+'/sys/schedule/schedule/delete?id='+scheduleId,
			type: 'POST',
			dataType: 'json',
			async : false
		})
		.done(function(data) {
			if(data){
				layer.alert("删除成功", {"offset":["40%","25%"]},function(){
							window.location.reload();
				});
			}else{
				parent.layer.alert("删除失败", 0);
			}
		}).fail(function(e) {
			parent.layer.alert("删除日程失败,请刷新页面后重试!", 0);
		});
	}
	
	
	//计算两个日期间相差的天数
	function _diffDays(date1, date2) {
		date1 = date1.split("-");
        date2 = date2.split("-");
        var start = new Date(date1[0], date1[1] - 1, date1[2]);
        var end = new Date(date2[0], date2[1] - 1, date2[2]);
        return parseInt((end - start) / 1000 / 60 / 60 / 24);
	}
	//比较两个时间的大小
	function _diffTimes(time1, time2) {
		if(time1==time2){
			return 0;
		}
		var h1 = parseInt(time1.split(":")[0]), m1 = parseInt(time1.split(":")[1]),
			h2 = parseInt(time2.split(":")[0]), m2 = parseInt(time2.split(":")[1]);
		if (h2 == h1) {
			return m2 > m1 ? 1 : -1;
		} else if (h2 > h1) {
			return 1;
		} else {
			return -1;
		}
	}

	//周视图和日视图中高亮显示今天
	function _bgToday() {
		var today = new Date().format("yyyy/M/d").substr(5);
		//周视图高亮显示"今天"
		$("body").on("click", ".fc-button-agendaWeek,.fc-button-today,.fc-button-prev,.fc-button-next", function () {
			$(".fc-view-agendaWeek thead > tr > th").each(function () {
				var span = $(this).find("span").length;
				var date = $(this).text().substr(4).replace("）", "");
				if (date == today && span == 0) $(this).wrapInner("<span class=\"bg-today\"></span>");
			});
		});
		//日视图高亮显示"今天"
		$("body").on("click", ".fc-button-agendaDay,.fc-button-today,.fc-button-prev,.fc-button-next", function () {
			var $view_day = $(".fc-view-agendaDay thead > tr > th:eq(1)");
			var span = $view_day.find("span").length;
			var date = $view_day.text().substr(4).replace("）", "");
			if (date == today && span == 0) $view_day.wrapInner("<span class=\"bg-today\"></span>");
		});
	}
	// 新建日程保存
	function saveNewScheduleV2(index){
		var that = $(this);
		that.find('.dg-btn-save').click(function(event) {
			//基础验证通过
			 if (_validate()) {
					 saveNewSchedule(index, false);
			 }
		});
	}

	function editScheduleV2(index){
		var that = $(this);
		that.find('.dg-btn-save').click(function(event) {
			//基础验证通过
    		if (_validate()) {
				saveModifySchedule();
    		}
		});
	}


	return {
		init: _initSchedule,
		add: _newSchedule,
		edit: _editSchedule,
		show: _showSchedule,
		today: _bgToday,
		del:delSchedule
	}
})();

$(function () {
	PRO.fullcalendar.add();
});
